<!--我的页面-->
<template>
  <div class="setContainer">
    <div class="setContainerTop">
      <div class="left">
        <div class="leftflex">
          <p class="txphoto" v-if="photo.length>0">
            <van-image round fit="cover" :src="photo" class="tximg" />
          </p>
          <p class="txphoto morentx" v-else>{{substringname(userDetails.name)}}</p>
        </div>
        <div class="rightflex">
          <p class="title">{{userDetails.name}}</p>
          <p class="depart">{{userDetails.department_type_name}}</p>
        </div>
      </div>
      <div class="right">{{userDetails.role_name}}</div>
    </div>
    <ul class="setContainer_ul clearfix1">
      <li
        class="setContainer_li"
        v-for="item in menulist"
        :key="item.id"
        @click="routeToName(item.name)"
      >
        <div class="flexlefr">
          <van-image :src="item.icon" :width="item.width" :height="item.height" class="listicon" />
          <span>{{item.name}}</span>
        </div>
        <div>
          <span class="banben">{{item.banben}}</span>
          <van-icon name="arrow" class="arrowright" v-if="item.id==1||item.id==2" />
          <!-- <van-icon class="arrowright" v-else/> -->
        </div>
      </li>
      <div class="divheight"></div>
      <li class="setContainer_li" @click="logoutbut">
        <div class="flexlefr">
          <van-image
            :src="menulist1[0].icon"
            :width="menulist1[0].width"
            :height="menulist1[0].height"
            class="listicon"
          />
          <span>{{menulist1[0].name}}</span>
        </div>
      </li>
    </ul>
    <!-- <p>平台{{platform}}</p> -->
    <van-action-sheet v-model="takephotoshow" :actions="actions" @select="takephotoSelect" />
    <!-- <button @click="takephoto">拍照</button> -->
    <!--加载框开始-->
    <van-overlay :show="showloading">
      <div class="wrapper">
        <div class="loadingcont">
          <van-loading size="24px" vertical>{{loaddingText}}</van-loading>
        </div>
      </div>
    </van-overlay>
    <!--加载框结束-->
  </div>
</template>
<script>
import { Dialog } from "vant";
import { mapState, mapMutations } from "vuex";
import { compressImage } from "../common/compressImage";
export default {
  computed: {
    ...mapState({
      userid: state => state.userData.id, // 加载 - Main
      token: state => state.Authorization,
      username: state => state.userData.name,
      role_id: state => state.userData.role_id
    })
  },
  data() {
    return {
      menulist1: [
        {
          id: 4,
          name: "退出登录",
          icon: require("../../../static/image/set_logout.png"),
          width: "18",
          height: "18"
        }
      ],
      menulist: [
        {
          id: 1,
          name: "设置头像",
          icon: require("../../../static/image/set_tx.png"),
          width: "18",
          height: "20"
        },
        {
          id: 2,
          name: "修改密码",
          icon: require("../../../static/image/set_pwd.png"),
          width: "18",
          height: "20"
        },
        {
          id: 3,
          name: "当前版本",
          icon: require("../../../static/image/set_bamb.png"),
          banben: "V1.1.6",
          width: "19",
          height: "19"
        }
      ],
      takephotoshow: false,
      actions: [
        { name: "相机", id: "1" },
        { name: "图库", id: "2" },
        { name: "取消", id: "3" }
      ],
      userDetails: {},
      photo: "",
      showloading: false,
      loaddingText: "上传图片中",
      platform: ""
    };
  },
  created() {
    this.GetUserDetails();
  },
  methods: {
    ...mapMutations(["logout"]),
    //取头像
    substringname(username) {
      if (username) {
        if (username.length >= 3) {
          return username.substr(username.length - 2, 2);
        } else {
          return username;
        }
      }
    },
    //获取详情
    GetUserDetails() {
      this.$toast.loading({
        mask: true,
        message: "加载中..."
      });
      var params = {
        id: this.userid,
        token: this.token
      };
      this.$http
        .get(`${this.$basePath}?service=App.User.GetUserDetails&api=83`, {
          params: params
        })
        .then(res => {
          if (res.ret == 200) {
            this.$toast.clear();
            this.userDetails = res.data;
            this.photo = res.data.photo;
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },
    //传照片接口
    UpdateUserPhoto() {
      var params = {
        token: this.token,
        id: this.userid,
        photo: this.photo
      };
      this.$http
        .post(
          `${this.$basePath}?service=App.User.UpdateUserPhoto&api=83`,
          params
        )
        .then(res => {
          if (res.ret == 200) {
            // this.GetUserDetails();
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },
    //选中图片方式，1是相机，2是图库
    takephotoSelect(item) {
      this.takephotoshow = false;
      if (item.id == 3) {
        this.$toast({ message: "取消上传图片" });
      } else if (item.id == 1) {
        this.cameraTakePicture();
      } else if (item.id == 2) {
        this.photoTakePicture();
      }
    },

    //实现将项目的图片转化成base64
    convertImgToBase64(url, callback, outputFormat) {
      var canvas = document.createElement("CANVAS"),
        ctx = canvas.getContext("2d"),
        img = new Image();
      img.crossOrigin = "Anonymous";
      img.onload = function() {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL(outputFormat || "image/png");
        callback.call(this, dataURL);
        canvas = null;
      };
      img.src = url;
    },
    //选中相册
    photoTakePicture() {
      //打开照相机
      let that = this;
      navigator.camera.getPicture(
        function(imageURI) {
          //打开摄像头成功的回调
          plugins.crop(
            function success(imageURI) {
              //裁剪成功的回调
              that.convertImgToBase64(imageURI, function(imageData) {
                //转化后的base64
                //查看大小
                var str = imageData.split(",")[1];
                var equalIndex = str.indexOf("=");
                if (str.indexOf("=") > 0) {
                  str = str.substring(0, equalIndex);
                }
                var strLen = str.length;
                var fileSize = strLen - (strLen / 8) * 2;
                var size = (fileSize / 1024).toFixed(2);
                if (parseInt(size) > 2048) {
                  compressImage(imageURI, {
                    width: 200,
                    quality: 0.4 // 压缩后图片的宽
                    // 压缩后图片的高，宽高若只传一个，则按图片原比例进行压缩
                    // 压缩后图片的清晰度，取值0-1，不传默认为0.7，值越小，所绘制出的图像越模糊
                  }).then(result => {
                    that.photo = result;
                    that.UpdateUserPhoto();
                  });
                } else {
                  that.photo = imageurl;
                  that.UpdateUserPhoto();
                }
              });
            },
            function fail() {
              //裁剪失败的回调
            },
            imageURI,
            { quality: 30 }
          ); //quality为照片质量
        },
        function() {
          //打开摄像头失败的回调
        },
        {
          quality: 50,
          destinationType: Camera.DestinationType.FILE_URI,
          // sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM
          sourceType: Camera.PictureSourceType.PHOTOLIBRARY
        }
      );
    },
    //拍照
    cameraTakePicture() {
      //打开照相机
      let that = this;
      navigator.camera.getPicture(
        function(imageURI) {
          //打开摄像头成功的回调
          plugins.crop(
            function success(imageURI) {
              //裁剪成功的回调
              that.convertImgToBase64(imageURI, function(imageData) {
                //转化后的base64
                //查看大小
                var str = imageData.split(",")[1];
                var equalIndex = str.indexOf("=");
                if (str.indexOf("=") > 0) {
                  str = str.substring(0, equalIndex);
                }
                var strLen = str.length;
                var fileSize = strLen - (strLen / 8) * 2;
                var size = (fileSize / 1024).toFixed(2);
                // alert("原文件大小:" + parseInt(size) + "kb");
                if (parseInt(size) > 2048) {
                  compressImage(imageURI, {
                    width: 200,
                    quality: 0.4 // 压缩后图片的宽
                  }).then(result => {
                    that.photo = result;
                    that.UpdateUserPhoto();
                  });
                } else {
                  that.photo = imageurl;
                  that.UpdateUserPhoto();
                }
              });
            },
            function fail() {
              //裁剪失败的回调
            },
            imageURI,
            { quality: 30 }
          ); //quality为照片质量
        },
        function() {
          //打开摄像头失败的回调
        },
        {
          quality: 50,
          destinationType: Camera.DestinationType.FILE_URI,
          sourceType: Camera.PictureSourceType.CAMERA
        }
      );
    },
    //退出登录
    logoutbut() {
      Dialog.confirm({
        title: "提示",
        message: "是否退出登录"
      })
        .then(() => {
          localStorage.clear();
          //退出时关闭websocket
          if (this.role_id == 3) {
            this.global.managerWs.send('{"type":"Maintenance"}');
            this.global.managerWs.close();
          }
          this.global.ws.send('{"type":"Maintenance"}');
          this.global.ws.close();
          this.logout();
          this.$router.push({
            //核心语句
            path: "/login" //跳转的路径
          });
        })
        .catch(() => {
          // on cancel
        });
    },
    routeToName(name) {
      switch (name) {
        case "设置头像":
          this.takephotoshow = true;
          break;
        case "修改密码":
          this.$router.push({
            //核心语句
            path: "/setNewPwd" //跳转的路径
          });
          break;

        default:
          this.$toast({
            message: "功能暂未开发"
          });
          break;
      }
    },
    //获取硬件
    onDeviceReady() {
      console.log(11111);
      console.log("设备上的cordova版本：", device.cordova);
      console.log("设备设备名称：", device.model);
      console.log("设备平台系统：", device.platform);
      console.log("设备唯一标识符：", device.uuid);
      console.log("设备平台操作系统版本号：", device.version);
      console.log("设备平台制造商：", device.manufacturer);
      this.platform = device.platform;
    }
  },
  mounted() {
    var that = this;
    document.addEventListener("deviceready", that.onDeviceReady, false);
  }
};
</script>
<style lang="less" scoped>
@import "../../assets/css/home";
.morentx {
  background: #fff;
  font-size: 25px;
  color: #0ad691;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}
</style>